﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace MyAMS.WebServer.Models
{
    /// <summary>
    /// 反伪造令牌
    /// </summary>
    public class AntiForgeryToken
    {
        /// <summary>
        /// Ticks名称
        /// </summary>
        public static readonly string TicksName = "__AntiForgeryTicks";

        /// <summary>
        /// 令牌名称
        /// </summary>
        public static readonly string TokenName = "__AntiForgeryToken";

        private readonly string salt;

        /// <summary>
        /// 初始化一个新的 <see cref="AntiForgeryToken"/> 类的实例
        /// </summary>
        /// <param name="salt">密钥</param>
        public AntiForgeryToken(string salt)
        {
            this.salt = salt;
            Ticks = getTicks();
        }

        /// <summary>
        /// 获取或设置Ticks
        /// </summary>
        public long Ticks { get; set; }

        /// <summary>
        /// 获取或设置令牌的值
        /// </summary>
        public string Value
        {
            get
            {
                return GetHash(salt, Ticks.ToString());
            }
        }

        private static long getTicks()
        {
            return DateTime.UtcNow.Ticks;
        }

        /// <summary>
        /// 获取散列
        /// </summary>
        /// <param name="salt"></param>
        /// <param name="ticks">ticks</param>
        /// <returns>散列</returns>
        public static string GetHash(string salt, string ticks)
        {
            byte[] bytesToHash = Encoding.UTF8.GetBytes(string.Concat(salt, ticks));

            SHA512 hasher = new SHA512Managed();
            byte[] hashed = hasher.ComputeHash(bytesToHash);

            return Convert.ToBase64String(hashed);
        }
    }
}
